﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using YioksPlanEditor.Tools;
using YioksPlanEditor.Yioks;

namespace YioksPlanEditor
{
    internal static class Program
    {
        [DllImport("user32.dll")]
        private static extern bool SetForegroundWindow(IntPtr hWnd);

        static Program()
        {

            FuctionTool.InitSoftData();
 
            var process = Process.GetCurrentProcess();
            var killOther = false;
            char[] chars = { '.', 'e', 'x', 'e' };
            var softName = YioksVar.SoftCfg.SoftName.TrimEnd(chars);
            var progressArr = Process.GetProcessesByName(softName);
            foreach (var p in progressArr)
            {
                if (p.MainModule != null && p.MainModule.ModuleName.TrimEnd(chars) == softName)
                {
                    if (p.Id == process.Id) continue;
                    var dialogResult = YioksMessageBox.Show(Properties.Resources.RestartNotice, Properties.Resources.ProxyNotice, MessageBoxButtons.YesNo,
                        MessageBoxIcon.Question, MessageBoxDefaultButton.Button2);
                    if (dialogResult == DialogResult.Yes)
                    {
                        killOther = true;
                        break;
                    }
                    else
                    {
                        SetForegroundWindow(p.MainWindowHandle);
                        process.CloseMainWindow();
                        process.Kill();
                        process.WaitForExit();
                        break;
                    }
                }
            }

            if (killOther)
            {
                progressArr = Process.GetProcessesByName(softName);
                foreach (var p in progressArr)
                {
                    if (p.MainModule != null && p.MainModule.ModuleName.TrimEnd(chars) == softName)
                    {
                        if (p.Id == process.Id) continue;
                        try
                        {
                            p.CloseMainWindow();
                            p.Kill();
                            p.WaitForExit();
                        }
                        catch {/**/ }
                    }
                }
            }
        }

        /// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        [STAThread]
        private static void Main(string[] pras)
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            #region 接受参数
            var userPra = new Dictionary<string, string>();
            foreach (var skey in pras)
            {
                var praInfo = skey.Split(':');
                if (praInfo.Length == 2)
                    userPra[praInfo[0]] = praInfo[1];
                else
                    userPra[skey] = "";
            }
            #endregion

            //获得当前登录的Windows用户标示  
            var identity = System.Security.Principal.WindowsIdentity.GetCurrent();
            var principal = new System.Security.Principal.WindowsPrincipal(identity);
            //判断当前登录用户是否为管理员  
            if (principal.IsInRole(System.Security.Principal.WindowsBuiltInRole.Administrator))
            {
                //是否启动卸载
                if (userPra.ContainsKey("uninst") || userPra.ContainsKey("uninstall"))
                {

                }
                else
                {
                    //如果是管理员，则直接运行  
                    //Application.Run(new FormStart());
                    Application.Run(new FormUnity());
                }
            }
            else
            {
                //创建启动对象  
                var startInfo = new ProcessStartInfo
                {
                    UseShellExecute = true,
                    WorkingDirectory = Environment.CurrentDirectory,
                    FileName = YioksVar.SoftCfg.SoftExecutablePath,
                    Verb = "runas"//设置启动动作,确保以管理员身份运行  
                };
                if (pras.Length > 0)
                    startInfo.Arguments = string.Join(",", pras);

                try
                {
                    Process.Start(startInfo);
                }
                catch
                {
                    return;
                }
                //退出  
                Application.Exit();
            }
        }
    }
}
